package com.fone.player.online.fragment;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;

import com.fone.player.R;
import com.fone.player.activity.BaseFragment;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.SoftRst;
import com.fone.player.client.SoftRst.Cnt;
import com.fone.player.entity.Download;
import com.fone.player.entity.SoftInfo;
import com.fone.player.online.adapter.SoftAdapter;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.view.ReGridView;
import com.fone.player.widget.xlistview.XListView;
import com.fone.player.widget.xlistview.XListView.IXListViewListener;

/**
 * 软件推荐页面
 */
public class SoftFragment extends BaseFragment implements IXListViewListener {
	/** 日志标签 */
	private static final String TAG = "SoftFragment";

	private View mView;
	private XListView mListView;

	private SoftAdapter adapter;

	private String url = "[host]/player/soft?page=1";
	private String nurl;

	private String shost;
	private String host;

	// private ArrayList<Cnt> softList = new ArrayList<Cnt>();
	private List<SoftInfo> softList = new ArrayList<SoftInfo>();

	private static final int SUCCESS = 0;
	private static final int FAILURE = 1;

	private boolean isFirst = true;

	private View mProgressContainer;
	private View mEmptyView;
	private boolean mContentShown;

	private void ensureContent() {
		if (mListView != null && mProgressContainer != null) {
			return;
		}
		View root = getView();
		if (root == null) {
			throw new IllegalStateException("Content view not yet created");
		}
		mProgressContainer = root.findViewById(R.id.progress);
		if (mProgressContainer == null) {
			throw new RuntimeException(
					"Your content must have a ViewGroup whose id attribute is 'R.id.progress_container'");
		}

		mEmptyView = root.findViewById(R.id.empty);
		if (mEmptyView != null) {
			mEmptyView.setVisibility(View.GONE);
		}
		mContentShown = true;

	}

	public void setContentEmpty(boolean isEmpty) {
		ensureContent();
		if (mListView == null) {
			throw new IllegalStateException(
					"List view must be initialized before");
		}
		if (isEmpty) {
			mEmptyView.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
		} else {
			mEmptyView.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
		}

	}

	private void setContentShown(boolean shown) {
		ensureContent();
		if (mContentShown == shown) {
			return;
		}
		mContentShown = shown;
		if (shown) {

			// mProgressContainer.startAnimation(AnimationUtils.loadAnimation(getActivity(),
			// android.R.anim.fade_out));
			// mListView.startAnimation(AnimationUtils.loadAnimation(getActivity(),
			// android.R.anim.fade_in));

			mProgressContainer.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
		} else {

			// mProgressContainer.startAnimation(AnimationUtils.loadAnimation(getActivity(),
			// android.R.anim.fade_in));
			// mListView.startAnimation(AnimationUtils.loadAnimation(getActivity(),
			// android.R.anim.fade_out));

			mProgressContainer.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
		}
	}

	public static SoftFragment newInstance(String url) {
		SoftFragment f = new SoftFragment();

		// Supply String input as an argument.
		Bundle args = new Bundle();
		args.putString("url", url);
		f.setArguments(args);
		return f;
	}

	public String getShownUrl() {
		return getArguments().getString("url");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		L.v(TAG, "---- onCreateView ----");

		mView = inflater.inflate(R.layout.fragment_soft, container, false);

		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		L.v(TAG, "---- onActivityCreated ----");
		initView();

	}

	@Override
	public void onStart() {
		super.onStart();
		L.v(TAG, "---- onStart ----");

		if (softList.isEmpty()) {
			// initSoftData(url);
			isFirst = true;
			setContentShown(false);
			onRefresh();
		}

	}

	private boolean initSoftData(String path) {

		L.v(TAG, "SoftCallBack", "initData()");
		// 如果没有网络，则不向服务器申请数据
		if (getActivity() != null && FoneUtil.isNetOkWithToast(getActivity())) {
			Request.getInstance().soft(FoneUtil.onlineUrl(path),
					new SoftCallBack());
			L.v(TAG, "initColumnData", FoneUtil.onlineUrl(path));
			return true;
		} else {
			setContentShown(true);
			return false;
		}

	}

	private void initView() {
		// ListView
		mListView = (XListView) mView.findViewById(R.soft.list);

		mListView.setPullLoadEnable(false);
		mListView.setPullRefreshEnable(true);
		mListView.setEnableDragLoadMore(false);
		mListView.setXListViewListener(this);
		// mListView.setOnScrollListener(this);

		mListView.setAdapter(new newsAdapter());

	}

	private class SoftCallBack implements Callback<SoftRst> {

		@Override
		public void onSuccess(SoftRst t) {
			if (destory) {
				return;
			}
			mListView.stopRefresh();
			mListView.stopLoadMore();

			updateSoft(t);
			setContentShown(true);
		}

		@Override
		public void onFailure(Error error) {
			if (destory) {
				return;
			}
			mListView.stopRefresh();
			mListView.stopLoadMore();

			L.v(TAG, "SoftCallBack", "-onFailure-" + error.toString());
			setContentShown(true);
		}

	}

	private void updateSoft(SoftRst t) {
		L.v(TAG, "SoftCallBack", "-onSuccess-" + t.result);
		if (getActivity() != null) {
			if (t.result == SUCCESS) {

				if (isFirst) {
					softList.clear();
					getServerData(t);
				}

				frashColumnListView(t);
				loadNextPage(t);
				isFirst = false;

			} else {
				// 数据返回不正确 不允许上拉加载更多,允许下拉刷新
				mListView.setPullRefreshEnable(false);
				mListView.setEnableDragLoadMore(false);
				mListView.setPullRefreshEnable(true);
			}
		}
	}

	/**
	 * 初始化服务器返回参数
	 */
	private void getServerData(SoftRst t) {
		if (t.shost != null) {
			shost = t.shost;
			L.v(TAG, "initServerInfo", "-shost-" + shost);
		}

		if (t.host != null) {
			host = t.host;
			L.v(TAG, "initServerInfo", "-host-" + host);
		}

	}

	/**
	 * 刷新"列表"数据
	 */
	private void frashColumnListView(SoftRst t) {
		// t.col.cnts.cntList
		if (t.col != null && t.col.cnts != null && t.col.cnts.cntList != null
				&& !t.col.cnts.cntList.isEmpty()) {

			for (Cnt cnt : t.col.cnts.cntList) {
				SoftInfo info = new SoftInfo();
				info.name = cnt.name;
				info.pic1 = cnt.pic1;
				info.url = cnt.url;
				softList.add(info);
			}

			if (adapter != null) {

				adapter.initData(shost, softList);
				adapter.notifyDataSetChanged();
			}
		}
	}

	/** "栏目"是否存在下一页 . */
	private void loadNextPage(SoftRst t) {
		if (t.col != null && t.col.rp != null && t.col.rp.m > t.col.rp.p
				&& t.col.rp.nurl != null) {
			nurl = t.col.rp.nurl;
			mListView.setEnableDragLoadMore(true);
			mListView.setPullLoadEnable(true);
		} else {
			// 隐藏上拉更多
			mListView.setEnableDragLoadMore(false);
			mListView.setPullLoadEnable(false);
		}
	}

	private class SoftItemClicker implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if (FoneUtil.isNetOkWithToast(getActivity())) {
				SoftInfo info = (SoftInfo) adapter.getItem(arg2);
				if (!TextUtils.isEmpty(info.url) && info.url.length() > 7) {
					String softurl = FoneUtil
							.getAbsoluteUrl(host, "", info.url)
							+ "&cipher="
							+ Request.getInstance().getCipher();
					String softImageUrl = FoneUtil.getAbsoluteUrl("", shost,
							info.pic1);
					Download download = new Download();
					download.setDownloadIsShowRunningNotification(true);
					download.setDownloadUrl(softurl);
					download.setDownloadImageUrl(softImageUrl);
					download.setDownloadFileName(info.name);
					download.setDownloadNotification(getActivity());
					download.setDownloadIsInstall(true);
					download.setDownloadIsErrorToast(true);
					download.setDownloadIsLimitSpeed(false);
					download.setDownloadType(Download.DOWNLOAD_RECOMMEND);
					int result = StorageModule.getInstance().addFileDownload(
							download);
					switch (result) {
					case 1:
						FoneUtil.showToast(getActivity(), "已经开始下载" + info.name
								+ "应用");
						break;
					case -1:
						FoneUtil.showToast(getActivity(), "该任务已经在下载队列");
						break;
					default:
						break;
					}

				}
			}
		}

	}

	@Override
	public void onRefresh() {
		mListView.onLoad();
		// 如果"栏目"下拉刷新
		if (initSoftData(url)) {
			isFirst = true;
		} else {
			mListView.stopRefresh();
			mListView.stopLoadMore();
		}
	}

	@Override
	public void onLoadMore() {
		if (initSoftData(nurl)) {
			mListView.setEnableDragLoadMore(false);
		} else {
			mListView.setEnableDragLoadMore(true);
			mListView.setPullLoadEnable(true);
		}

	}

	private class newsAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return 1;

		}

		@Override
		public Object getItem(int position) {
			return null;

		}

		@Override
		public long getItemId(int position) {
			return position;

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// View v = LayoutInflater.from(getActivity()).inflate(
			// R.layout.view_soft, null);
			// ReGridView grid = (ReGridView) v.findViewById(R.soft.gridview);
			// adapter = new SoftAdapter(getActivity(), shost, softList);
			// grid.setAdapter(adapter);
			// grid.setOnItemClickListener(new SoftItemClicker());
			// return v;

			ViewHolder vHolder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(getActivity()).inflate(
						R.layout.view_soft, null);
				vHolder = new ViewHolder();
				vHolder.grid = (ReGridView) convertView
						.findViewById(R.soft.gridview);
				convertView.setTag(vHolder);
			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}

			adapter = new SoftAdapter(getActivity(), shost, softList);
			vHolder.grid.setAdapter(adapter);
			vHolder.grid.setOnItemClickListener(new SoftItemClicker());

			return convertView;

		}
	}

	static class ViewHolder {
		ReGridView grid;
	}

	/**
	 * Detach from view.
	 */
	@Override
	public void onDestroyView() {
		mContentShown = false;

		mProgressContainer = mEmptyView = null;
		destory = true;

		if (mListView != null) {
			mListView.removeAllViewsInLayout();
		}

		mListView = null;

		super.onDestroyView();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		System.out.println(TAG + "---- onDestroy ----");
	}

}
